<script setup lang="ts">
// @ts-nocheck
import { ref, reactive, onMounted, h, computed } from 'vue';
import { Card, Form, Input, Button, Table, DatePicker, message, Tabs, Statistic, Row, Col, Modal as AModal, Select } from 'ant-design-vue';
import dayjs from 'dayjs';
import { addUser, getUsers, updateUser, getVisitCount } from '#/api';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

void [Card, Form, Input, Button, Table, DatePicker, Tabs, Statistic, Row, Col, AModal, Select];

const loading = ref(false);
const dataSource = ref<any[]>([]);
const pagination = reactive({ current: 1, pageSize: 10, total: 0 });
const activeTab = ref('stats');

const searchForm = reactive({
  nickname: '',   // 仅按微信名搜索
});

// 新增/编辑弹窗
const modalVisible = ref(false);
const modalTitle = ref('新增用户');
const modalLoading = ref(false);
const isEdit = ref(false);
const userForm = reactive({
  id: undefined as string | number | undefined,
  nickname: '',
  tel: '',
  gender: undefined as number | undefined,
  address: '',
});

// 用户统计数据
const statsLoading = ref(false);
const statsRange = ref([dayjs().subtract(7, 'day'), dayjs().subtract(1, 'day')]);
const userStats = ref<Array<{ date: string; count: number }>>([
  { date: dayjs().subtract(6, 'day').format('YYYY-MM-DD'), count: 0 },
  { date: dayjs().subtract(5, 'day').format('YYYY-MM-DD'), count: 0 },
  { date: dayjs().subtract(4, 'day').format('YYYY-MM-DD'), count: 0 },
  { date: dayjs().subtract(3, 'day').format('YYYY-MM-DD'), count: 0 },
  { date: dayjs().subtract(2, 'day').format('YYYY-MM-DD'), count: 0 },
  { date: dayjs().subtract(1, 'day').format('YYYY-MM-DD'), count: 0 },
  { date: dayjs().format('YYYY-MM-DD'), count: 0 },
]);

// 访问统计
const visitCount = ref(0);

// 图表相关
const chartRef = ref();
const { renderEcharts } = useEcharts(chartRef);

const totalUsers = computed(() => {
  return userStats.value.reduce((sum, item) => sum + item.count, 0);
});

const averageUsers = computed(() => {
  return Math.round(totalUsers.value / userStats.value.length);
});

// 获取访问统计
async function fetchVisitCount() {
  try {
    const res = await getVisitCount();
    console.log('visitCount', res);
    visitCount.value = typeof res === 'number' ? res : (res?.count ?? 0);
  } catch {
    visitCount.value = 0;
  }
}

const columns = [
  { title: '微信名', dataIndex: 'nickname', key: 'nickname' },
  { title: '性别', dataIndex: 'gender', key: 'gender' },
  { title: '手机号', dataIndex: 'tel', key: 'tel' },
  { title: '地址', dataIndex: 'address', key: 'address' },
  { title: '访问次数', dataIndex: 'visitCount', key: 'visitCount' },
  {
    title: '操作',
    key: 'action',
    customRender: ({ record }: any) =>
      h(Button, { type: 'link', size: 'small', onClick: () => openEditModal(record) }, '编辑'),
  },
];

async function fetchList() {
  // 组装后端要求的 POST 入参
  const kw = (searchForm.keyword || '').trim();
  const payload = {
    nickname: searchForm.nickname.trim() || undefined,
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
  };

  try {
    loading.value = true;
    const resp: any = await getUsers(payload);
    const list = Array.isArray(resp?.data?.records)
      ? resp.data.records
      : Array.isArray(resp?.records)
        ? resp.records
        : Array.isArray(resp?.list)
          ? resp.list
          : (Array.isArray(resp) ? resp : []);
    const total = typeof resp?.data?.total === 'number'
      ? resp.data.total
      : typeof resp?.total === 'number'
        ? resp.total
        : list.length;

    dataSource.value = list.map((m: any) => ({
      id: m.id ?? `${Math.random()}`,
      nickname: m.nickname ?? m.nickName ?? m.name ?? '-',
      gender: m.gender ?? '-',
      tel: m.tel ?? m.mobile ?? m.phone ?? '-',
      address: m.address ?? '-',
      visitCount: typeof m.visitCount === 'number' ? m.visitCount : (m.visit_count ?? 0),
    }));

    pagination.total = total;
  } catch (e) {
    message.error('加载用户列表失败');
  } finally {
    loading.value = false;
  }
}

function handleSearch() {
  pagination.current = 1;
  fetchList();
}

function handleReset() {
  searchForm.nickname = '';
  pagination.current = 1;
  fetchList();
}

function handleTableChange(p: any) {
  pagination.current = p.current;
  pagination.pageSize = p.pageSize;
  fetchList();
}

async function fetchUserStats() {
  statsLoading.value = true;
  try {
    // 计算日期范围内的天数
    const days = statsRange.value[1].diff(statsRange.value[0], 'day') + 1;
    
    // 逐天调用接口
    const promises = [];
    for (let i = 0; i < days; i++) {
      const date = statsRange.value[0].add(i, 'day').format('YYYY-MM-DD');
      promises.push(
        getVisitCount({ startTime: date, endTime: date })
          .then(res => ({ date, res }))
          .catch(err => ({ date, res: null, error: err }))
      );
    }
    
    // 并发请求所有日期
    const results = await Promise.all(promises);
    console.log('fetchUserStats results:', results);
    
    // 解析每天的数据
    userStats.value = results.map(({ date, res }) => {
      let count = 0;
      
      console.log(`解析日期 ${date} 的数据:`, res);
      
      // 根据后端返回的数据结构解析
      if (res) {
        // 可能的返回格式：
        // 1. { data: { count: number } }
        // 2. { data: { todayCount: number } }
        // 3. { count: number }
        // 4. { data: number }
        // 5. number
        if (typeof res === 'number') {
          count = res;
        } else if (typeof res?.count === 'number') {
          count = res.count;
        } else if (typeof res?.data?.count === 'number') {
          count = res.data.count;
        } else if (typeof res?.data?.todayCount === 'number') {
          count = res.data.todayCount;
        } else if (typeof res?.data === 'number') {
          count = res.data;
        } else if (typeof res?.visitCount === 'number') {
          count = res.visitCount;
        } else if (typeof res?.data?.visitCount === 'number') {
          count = res.data.visitCount;
        }
      }
      
      console.log(`日期 ${date} 解析后的count:`, count);
      return { date, count };
    });
    
    console.log('最终的userStats:', userStats.value);
    
    renderUserChart();
  } catch (e) {
    console.error('获取用户统计失败:', e);
    message.error('获取用户统计失败');
  } finally {
    statsLoading.value = false;
  }
}

function handleStatsSearch() {
  fetchUserStats();
}

async function handleModalSubmit() {
  const { nickname, tel, gender, address } = userForm;
  if (!nickname || !tel) {
    message.warning('请填写微信名和手机号');
    return;
  }
  modalLoading.value = true;
  try {
    if (isEdit.value) {
      await updateUser({ id: userForm.id!, nickname, tel, gender, address });
      message.success('编辑成功');
    } else {
      await addUser({ nickname, tel, gender, address });
      message.success('新增成功');
    }
    modalVisible.value = false;
    resetModal();
    await fetchList();
  } catch {
    message.error(isEdit.value ? '编辑失败' : '新增失败');
  } finally {
    modalLoading.value = false;
  }
}

function resetModal() {
  Object.assign(userForm, {
    id: undefined,
    nickname: '',
    tel: '',
    gender: '',
    address: '',
  });
  isEdit.value = false;
}

function openAddModal() {
  modalTitle.value = '新增用户';
  modalVisible.value = true;
}

function openEditModal(record: any) {
  modalTitle.value = '编辑用户';
  isEdit.value = true;
  // 性别文字转数字
  const genderMap: Record<string, number> = { '男': 1, '女': 2 };
  Object.assign(userForm, {
    id: record.id,
    nickname: record.nickname,
    tel: record.tel,
    gender: genderMap[record.gender as string] ?? undefined,
    address: record.address,
  });
  modalVisible.value = true;
}

function renderUserChart() {
  const dates = userStats.value.map(item => item.date);
  const counts = userStats.value.map(item => item.count);
  
  renderEcharts({
    grid: {
      bottom: 30,
      containLabel: true,
      left: '3%',
      right: '4%',
      top: 30,
    },
    series: [
      {
        areaStyle: {
          opacity: 0.3
        },
        data: counts,
        itemStyle: {
          color: '#1677ff',
        },
        name: '用户数量',
        smooth: true,
        type: 'line',
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
    },
    yAxis: {
      type: 'value',
      name: '用户数量',
    }
  });
}

onMounted(() => {
  fetchList();
  fetchUserStats();
  fetchVisitCount();
});
</script>

<template>
  <div class="p-4">
    <Card>
      <template #title>
        用户管理与统计
      </template>
      
      <Tabs v-model:activeKey="activeTab">
        <Tabs.TabPane key="stats" tab="用户统计">
          <div class="mb-6">
            <Row :gutter="16">
              <Col :span="12">
                <Card>
                  <Statistic title="总用户数" :value="totalUsers" :precision="0" />
                </Card>
              </Col>
              <!-- <Col :span="6">
                <Card>
                  <Statistic title="平均每日用户" :value="averageUsers" :precision="0" />
                </Card>
              </Col> -->
              <Col :span="12">
                <Card>
                  <Statistic title="今日用户" :value="visitCount?.data?.todayCount || 0" :precision="0" />
                </Card>
              </Col>
              <!-- <Col :span="8">
                <Card>
                  <Statistic title="访问统计" :value="visitCount" :precision="0" />
                </Card>
              </Col> -->
            </Row>
          </div>
          
          <div class="mb-4 flex items-center gap-2">
            <DatePicker.RangePicker 
              v-model:value="statsRange" 
              :disabled-date="(current) => current && current >= dayjs().startOf('day')"
              :allowClear="false"
            />
            <Button type="primary" :loading="statsLoading" @click="handleStatsSearch">查询</Button>
          </div>
          
          <div class="border rounded p-4" style="height: 400px;">
            <EchartsUI ref="chartRef" style="height: 100%;" />
          </div>
          
          <div class="mt-4 border rounded">
            <div class="grid grid-cols-2 font-medium bg-gray-50 px-3 py-2">
              <div>日期</div>
              <div>用户数量</div>
            </div>
            <div v-for="item in userStats" :key="item.date" class="grid grid-cols-2 px-3 py-2 border-t">
              <div>{{ item.date }}</div>
              <div>{{ item.count }}</div>
            </div>
          </div>
        </Tabs.TabPane>
        
        <Tabs.TabPane key="table" tab="用户列表">
          <div class="mb-4">
            <Form layout="inline">
              <Form.Item label="微信名称">
                <Input v-model:value="searchForm.nickname" class="w-60" placeholder="请输入微信名称" />
              </Form.Item>
              <Form.Item>
                <Button type="primary" :loading="loading" @click="handleSearch">搜索</Button>
              </Form.Item>
              <Form.Item>
            <Button :disabled="loading" @click="handleReset">重置</Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" @click="openAddModal">新增用户</Button>
          </Form.Item>
        </Form>
          </div>

          <Table
            :columns="columns"
            :dataSource="dataSource"
            :loading="loading"
            :pagination="{ current: pagination.current, pageSize: pagination.pageSize, total: pagination.total, showSizeChanger: true }"
            :rowKey="(r: any) => r.id"
            @change="handleTableChange"
          />
        </Tabs.TabPane>
      </Tabs>
    </Card>

    <!-- 新增/编辑弹窗 -->
    <AModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleModalSubmit"
      @cancel="resetModal"
    >
      <Form layout="vertical">
        <Form.Item label="微信名" required>
          <Input v-model:value="userForm.nickname" placeholder="请输入微信名" />
        </Form.Item>
        <Form.Item label="手机号" required>
          <Input v-model:value="userForm.tel" placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item label="性别">
          <Select v-model:value="userForm.gender" placeholder="请选择性别">
            <Select.Option :value="1">男</Select.Option>
            <Select.Option :value="2">女</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="地址">
          <Input v-model:value="userForm.address" placeholder="请输入地址" />
        </Form.Item>
      </Form>
    </AModal>
  </div>
</template>